package playing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PlayerFriendships extends JFrame {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/ZUT";
    private static final String USER = "root";
    private static final String PASS = "123456";

    public PlayerFriendships() {

        setTitle("Player Friendships");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        Container container = getContentPane();
        container.setLayout(new GridLayout(6, 1));

        JLabel playerIdLabel = new JLabel("Player ID:");
        JTextField playerIdField = new JTextField();
        JLabel friendIdLabel = new JLabel("Friend ID:");
        JTextField friendIdField = new JTextField();

        JButton addButton = new JButton("Add Friend");
        JButton deleteButton = new JButton("Delete Friend");
        JButton listButton = new JButton("List All Friends");

        JTextArea outputArea = new JTextArea();
        outputArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(outputArea);

        container.add(playerIdLabel);
        container.add(playerIdField);
        container.add(friendIdLabel);
        container.add(friendIdField);
        container.add(addButton);
        container.add(deleteButton);
        container.add(listButton);
        container.add(scrollPane);

        // 按钮事件处理
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int playerId = Integer.parseInt(playerIdField.getText());
                int friendId = Integer.parseInt(friendIdField.getText());
                addFriend(playerId, friendId);
                outputArea.setText("添加成功!");
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int playerId = Integer.parseInt(playerIdField.getText());
                int friendId = Integer.parseInt(friendIdField.getText());
                deleteFriend(playerId, friendId);
                outputArea.setText("删除成功!");
            }
        });

        listButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int playerId = Integer.parseInt(playerIdField.getText());
                List<Integer> friendIds = getAllFriendIds(playerId);
                StringBuilder sb = new StringBuilder();
                for (int id : friendIds) {
                    sb.append("Friend ID: ").append(id).append("\n");
                }
                outputArea.setText(sb.toString());
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PlayerFriendships().setVisible(true);
            }
        });
    }

    // 添加好友
    public static void addFriend(int playerId, int friendId) {
        String sqlCheck = "SELECT * FROM friendships WHERE player_id = ? AND friend_id = ?";
        String sqlInsert = "INSERT INTO friendships (player_id, friend_id) VALUES (?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement pstmtCheck = conn.prepareStatement(sqlCheck);
             PreparedStatement pstmtInsert = conn.prepareStatement(sqlInsert)) {

            pstmtCheck.setInt(1, playerId);
            pstmtCheck.setInt(2, friendId);
            ResultSet rs = pstmtCheck.executeQuery();
            if (!rs.next()) {
                pstmtInsert.setInt(1, playerId);
                pstmtInsert.setInt(2, friendId);
                pstmtInsert.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除好友
    public static void deleteFriend(int playerId, int friendId) {
        String sql = "DELETE FROM friendships WHERE player_id = ? AND friend_id = ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, playerId);
            pstmt.setInt(2, friendId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    // 获取所有好友ID
    public static List<Integer> getAllFriendIds(int playerId) {
        String sql = "SELECT friend_id FROM friendships WHERE player_id = ?";
        List<Integer> friendIds = new ArrayList<>();

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, playerId);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                int friendId = rs.getInt("friend_id");
                friendIds.add(friendId);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return friendIds;
    }
    // 打印单个用户ID对应的用户名
    public void printUserById(int userId) {
        String sql = "SELECT username FROM users WHERE users_id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    String username = rs.getString("username");
                    System.out.println("用户ID: " + userId + ", 用户姓名: " + username);
                } else {
                    System.out.println("用户ID " + userId + " 未找到对应的用户");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 遍历List并打印所有用户ID对应的用户名
    public void printAllUsersByIdList(List<Integer> userIdList) {
        for (int userId : userIdList) {
            printUserById(userId);
        }

    }




    //查询好友是否存在
    public static boolean isFriend(int playerId, int friendId) {
        String sql = "SELECT * FROM friendships WHERE player_id = ? AND friend_id = ?";
        boolean isFriendExists = false;

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, playerId);
            pstmt.setInt(2, friendId);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) { // 如果找到了这样的记录，说明好友存在
                isFriendExists = true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return isFriendExists;
    }

}